package com.senthink.gl.business.userlog.business;

import com.senthink.gl.business.auth.RegisterUserRequest;
import com.senthink.gl.business.auth.UpdateUserRequest;
import com.senthink.gl.business.forgetpw.ForgetPasswordRequest;
import com.senthink.gl.business.security.JwtTokenUtils;
import com.senthink.gl.business.userlog.enums.LogDetailEnum;
import com.senthink.gl.business.userlog.SystemUserLog;
import com.senthink.gl.business.domain.entity.UserLog;
import com.senthink.gl.business.domain.entity.User;
import com.senthink.gl.business.domain.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;


/**
 * 登录操作记录类
 * @author yuanpeng@senthink.com
 * @data 2018-01-31 16:57
 */

@Component
public class LogUserBusiness {

    @Autowired
    private UserService userService;

    @Value("${jwt.prefix}")
    private String tokenPrefix;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;


    public void main(SystemUserLog systemUserLog, UserLog userLog, JoinPoint joinPoint, HttpServletRequest request) {
        if (systemUserLog.detail() == LogDetailEnum.LOGIN_IN) {
            loginIn(userLog, joinPoint, request);
        } else if (systemUserLog.detail() == LogDetailEnum.FORGET_PASSWORD) {
            forgetPw(userLog, joinPoint);
        } else if (systemUserLog.detail() == LogDetailEnum.UPDATE_USER) {
            update(userLog, joinPoint, request);
        } else if (systemUserLog.detail() == LogDetailEnum.DELETE_USER) {
            delete(userLog, joinPoint, request);
        } else if (systemUserLog.detail() == LogDetailEnum.CREATE_USER) {
            create(userLog, joinPoint, request);
        } else if (systemUserLog.detail() == LogDetailEnum.ENABLE_USER) {
            enable(userLog, joinPoint, request);
        }
    }

    /**
     * 修改用户状态
     * @param userLog
     * @param joinPoint
     * @param request
     */
    private void enable(UserLog userLog, JoinPoint joinPoint, HttpServletRequest request) {
        String uid = (String)joinPoint.getArgs()[0];
        User user = userService.findByUid(uid)
                .orElse(null);
        userLog.setDetails(LogDetailEnum.ENABLE_USER.getDetail() + ":" + (user==null?"unknown":user.getName()));
    }

    /**
     * 用户登录
     * @param userLog
     * @param joinPoint
     * @param request
     */
    private void loginIn(UserLog userLog, JoinPoint joinPoint, HttpServletRequest request){
        String account = (String)joinPoint.getArgs()[0];
        User user = userService.findByAccount(account)
                .orElse(null);
        if (user != null) {
            userLog.setUid(user.getUid());
            userLog.setRole(user.getRole());
        } else {
            userLog.setUid("unknown");
            userLog.setRole("unknown");
        }
        userLog.setDetails(LogDetailEnum.LOGIN_IN.getDetail() + ":" + userLog.getIp());
    }

    /**
     * 忘记密码
     * @param userLog
     * @param joinPoint
     */
    private void forgetPw(UserLog userLog, JoinPoint joinPoint) {
        ForgetPasswordRequest forgetPasswordRequest = (ForgetPasswordRequest)joinPoint.getArgs()[0];
        User user = userService.findByAccount(forgetPasswordRequest.getAccount())
                .orElse(null);
        if (user != null) {
            userLog.setUid(user.getUid());
            userLog.setRole(user.getRole());
        } else {
            userLog.setUid("unknown");
            userLog.setRole("unknown");
        }
        userLog.setDetails(LogDetailEnum.FORGET_PASSWORD.getDetail() + ":" + userLog.getIp());
    }

    /**
     * 用户信息编辑 ：编辑用户中心，管理员编辑信息
     * @param userLog
     * @param joinPoint
     * @param request
     */
    private void update(UserLog userLog, JoinPoint joinPoint, HttpServletRequest request) {
        UpdateUserRequest updateUserRequest = (UpdateUserRequest) joinPoint.getArgs()[0];
        String token = request.getHeader(tokenHeader);
        String tokenPayload = token.substring(tokenPrefix.length());
        String username = jwtTokenUtils.getUsernameFromToken(tokenPayload);
        User rootUser = userService.findByAccount(username)
                .orElse(null);
        User user = userService.findByAccount(updateUserRequest.getAccount())
                .orElse(null);
        if (user != null) {
            userLog.setUid(rootUser.getUid());
            userLog.setRole(rootUser.getRole());
            if (username.equals(user.getAccount())) {
                userLog.setDetails(LogDetailEnum.UPDATE_CENTER.getDetail());
            } else {
                userLog.setDetails(LogDetailEnum.UPDATE_USER.getDetail() + ":" +user.getAccount());
            }
        } else {
            userLog.setUid("unknown");
            userLog.setRole("unknown");
        }
    }

    /**
     * 管理员删除用户
     * @param userLog
     * @param joinPoint
     * @param request
     */
    private void delete(UserLog userLog, JoinPoint joinPoint, HttpServletRequest request) {
        UpdateUserRequest updateUserRequest = (UpdateUserRequest) joinPoint.getArgs()[0];
        String token = request.getHeader(tokenHeader);
        String tokenPayload = token.substring(tokenPrefix.length());
        String username = jwtTokenUtils.getUsernameFromToken(tokenPayload);
        User rootUser = userService.findByAccount(username)
                .orElse(null);
        User user = userService.findByUid(updateUserRequest.getUid())
                .orElse(null);
        if (user != null) {
            userLog.setUid(rootUser.getUid());
            userLog.setRole(rootUser.getRole());
            userLog.setDetails(LogDetailEnum.DELETE_USER.getDetail()+ ":" +user.getAccount());
        } else {
            userLog.setUid("unknown");
            userLog.setRole("unknown");
        }
    }

    /**
     * 新增用户
     * @param userLog
     * @param joinPoint
     * @param request
     */
    private void create(UserLog userLog, JoinPoint joinPoint, HttpServletRequest request) {
        RegisterUserRequest registerUserRequest = (RegisterUserRequest)joinPoint.getArgs()[0];
        String token = request.getHeader(tokenHeader);
        String tokenPayload = token.substring(tokenPrefix.length());
        String username = jwtTokenUtils.getUsernameFromToken(tokenPayload);
        User rootUser = userService.findByAccount(username)
                .orElse(null);
        User user = userService.findByAccount(registerUserRequest.getAccount())
                .orElse(null);
        if (user != null) {
            userLog.setUid(rootUser.getUid());
            userLog.setRole(rootUser.getRole());
            userLog.setDetails(LogDetailEnum.CREATE_USER.getDetail()+ ":" +registerUserRequest.getRole() +"," +registerUserRequest.getAccount());
        } else {
            userLog.setUid("unknown");
            userLog.setRole("unknown");
        }
    }
}
